import pyperclip
from flask import Flask, render_template_string
import pandas as pd

app = Flask(__name__)
paste_text = '用友'
data_path = '/切勿外传1.xlsx'

try:
    # 读取Excel文件
    df = pd.read_excel(data_path)
    # 获取标题行
    headers = df.columns.tolist()
    # 将DataFrame转换为列表
    all_lines = df.values.tolist()
    print(f"读取文件 {data_path} 成功")
except FileNotFoundError:
    headers = []
    all_lines = []
    print(f"文件 {data_path} 未找到")
except Exception as e:
    headers = []
    all_lines = []
    print(f"读取文件时发生错误: {e}")


@app.route('/answer')
def answer():
    script = "<script>setTimeout(function () {window.location.reload();}, 3000);</script>"
    paste_text = pyperclip.paste()
    print(paste_text)
    # print('所有数据', all_lines)

    if not paste_text:
        lines = all_lines[:10]
    else:
        lines = [headers]  # 保留标题行
        for l in all_lines:
            if any(paste_text.lower() in str(cell).lower() for cell in l):
                lines.append(l)
            if len(lines) > 11:  # 包含标题行，所以最多11行
                break

    # 将列表转换为HTML格式
    print('123', lines)

    # 创建HTML表格
    html = "<table border='1' style='border-collapse: collapse; width: 100%;'>"

    # 添加标题行
    html += "<tr>"
    for header in headers:
        html += f"<th>{header}</th>"
    html += "</tr>"

    # 添加数据行
    for line in lines[1:]:  # 跳过标题行
        html += "<tr>"
        for cell in line:
            cell_str = str(cell)
            if paste_text.lower() in cell_str.lower():
                # 高亮显示匹配的内容
                highlighted_cell = cell_str.replace(paste_text, f"<span style='background-color: yellow;'>{paste_text}</span>")
                html += f"<td>{highlighted_cell}</td>"
            else:
                html += f"<td>{cell_str}</td>"
        html += "</tr>"

    html += "</table>"

    return script + html


if __name__ == '__main__':
    app.run(debug=False, threaded=True, port=26888, host='0.0.0.0')
